package fr.upmc.aladyn.methodcallinterception;
import java.util.ArrayList;

import fr.upmc.aladyn.shared.ObjetTrans;
import fr.upmc.aladyn.annotation.Transactionable;

/**
 * Class containing methods used to simulate basic transactions
 * 
 * @author Thierry Wong
 * @author Seyyid ahmed Ouir
 */

@Transactionable
public class Scenario {

	private ArrayList<ObjetTrans> tabObj;
	private String[] names = {"o1","o2","o3",
							  "o4","o5","o6",
							  "o7","o8"};
	
	/**
	 * Default constructor
	 */
	public Scenario() 
	{
		tabObj = new ArrayList<ObjetTrans>();
		for (int i = 0; i < 8; i++)
		{
			System.out.println(i);
			tabObj.add(new ObjetTrans(names[i],(i + 1)));
		}
	}

	@Transactionable
	public void m0()
	{
		System.out.println("m0");
		this.tabObj.get(0).setName("o1_modif*1*");
		this.m1();
		try {
			this.m2();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * Non transactionable method. Does some modifications.
	 */
	@Transactionable
	public void m1() 
	{
		System.out.println("m1");
		System.out.println(this.toString());
		this.tabObj.get(1).setName("o2_modif");
		this.tabObj.get(2).setName("o3_modif");
	}
	
	/**
	 * Method throwing an Exception to activate transaction restoration
	 * @param i an <code> int </code> value
 	 * @throws Exception 
	 */
	@Transactionable
	public void m2() throws Exception 
	{
		System.out.println("m2");
		System.out.println(this.toString());
		this.tabObj.get(3).setName("o4_modif");
		this.tabObj.get(0).setName("o1_modif*2*");
		this.m3();
		this.tabObj.get(7).setName("o8_modif");
		throw new Exception();
	}

	/**
	 * Transactionable method. Does some modifications.
	 */
	@Transactionable
	public void m3() 
	{
		System.out.println("m3");
		System.out.println(this.toString());
		try 
		{
			this.tabObj.get(4).setName("o5_modif");
			this.tabObj.get(5).setName("o6_modif");
			throw new Exception();
		} 
		catch(Exception e){}
		this.tabObj.get(6).setName("o7_modif");
	}
	
	private ArrayList<ObjetTrans> getTabObj(){
		return this.tabObj;
	}
	
	public String toString()
	{
		String s = "[";
		for (ObjetTrans o : this.getTabObj()){
			s += o.getName() + " ";
		}
		return s + "]";
	}

	public static void main(String[] args) throws Exception {
		Scenario p = null;
		p = new Scenario();
		System.out.println(p.toString());
		p.m0();
		System.out.println(p.toString());
	}

}
